package com.joinway.mobile.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.joinway.common.bean.domain.UserCheckout;
import com.joinway.framework.bean.view.View;
import com.joinway.framework.data.jdbc.repository.TableRepository;
import com.joinway.framework.ecshop.bean.domain.RegExtendInfo;
import com.joinway.framework.ecshop.bean.domain.User;
import com.joinway.mobile.bean.view.UserCheckoutView;
import com.joinway.mobile.bean.view.UserView;
import com.joinway.mobile.exception.MobileErrorConstants;
import com.joinway.mobile.exception.MobileException;

@Service
public class UserService {

	private final static Logger log = LoggerFactory.getLogger(UserService.class);
	
	@Autowired TableRepository repository;
	
	public UserView getProfile(int userId) throws Exception {
//		log.info("user id is {}", userId);
//		User user = repository.findById(User.class, userId, "login_user");
		UserView view;
		List<UserView> views = repository.find(UserView.class, SqlFactory.createFindUpserProfileSql(userId));
		
		if(CollectionUtils.isNotEmpty(views)){
			view = views.get(0);
//			view.setName(user.getUserName());
//			view.setGender(EcShopUtils.getGender(user.getSex()));
//			view.setCellPhone(user.getMobilePhone());
		}else{
			throw new MobileException(MobileErrorConstants.USER_NO_EXISTS);
		}
		
		return view;
	}
	
	@Transactional(rollbackFor=Throwable.class)
	public View updateProfile(int userId, String name, String gender) throws Exception {
		View view = new View();
		
		User user = repository.findById(User.class, userId, "login_user");
		
		if(user != null){
			int sex = 0;
			if("M".equalsIgnoreCase(gender)){
				sex = 1;
			}else if("F".equalsIgnoreCase(gender)){
				sex = 2;
			}
			user.setSex(sex);
			
			repository.save(user, "login_user");
			
			String sql = "select * from reg_extend_info where user_id = ? and reg_field_id = 100";
			List<RegExtendInfo> infos = repository.find(RegExtendInfo.class, sql, userId);
			if(CollectionUtils.isNotEmpty(infos)){
				RegExtendInfo info = infos.get(0);
				info.setContent(name);
				repository.save(info);
			}
		}else{
			throw new MobileException(MobileErrorConstants.USER_NO_EXISTS);
		}
		
		return view;
	}
	
	@Transactional(rollbackFor=Throwable.class)
	public UserCheckoutView checkout(int userId) throws Exception{
		int points = (int)(50*Math.random()+50);
		UserCheckout userCheckout = new UserCheckout();
		userCheckout.setPoints(points);
		userCheckout.setUserId(userId);
		userCheckout.setCheckoutTime(new Date());
		repository.save(userCheckout);
		
		UserCheckoutView userCheckoutView = new UserCheckoutView();
		userCheckoutView.setPoints(String.valueOf(points));
		
		return userCheckoutView;
	}
}
